package com.example.account;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.account.Adapter.TypeDataAdapter;
import com.example.account.DataBase.AccountData;
import com.example.account.DataBase.AccountDataBase;
import com.example.account.DataBase.AccountDataDao;
import com.example.account.DataBase.TypeData;
import com.example.account.DataBase.TypeDataDao;
import com.example.account.DataBase.TypeDatabase;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

//支出模块
public class InFragment extends Fragment implements View.OnClickListener {
    KeyboardView my;
    EditText et;
    ImageView iv;
    TextView tv_type, tv_bz, tv_time;
    GridView gv;
    private static TypeDatabase typeDatabase;
    private static TypeDataDao typeDataDao;
    private AccountDataBase accountDataBase;
    private AccountDataDao accountDataDao;
    private static List<TypeData> sin = new ArrayList<>();
    private static TypeDataAdapter adapter;
    private AccountData accountData;
    private Intent intent;
    private String model;
    private int lasid;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        typeDatabase = TypeDatabase.getDatabase(getContext());
        typeDataDao = (TypeDataDao) typeDatabase.getDataDao();
        accountDataBase = AccountDataBase.getDatabase(getContext());
        accountDataDao = accountDataBase.getDataDao();
        intent = getActivity().getIntent();
        accountData = new AccountData();
        model = intent.getStringExtra("type");
        System.out.println("取出的type值为" + model);
    }

    private void updateshow() {
        lasid = Integer.parseInt(intent.getStringExtra("id"));
        System.out.println("取出的id值为" + lasid);
        accountData = accountDataDao.FindById(lasid);
        System.out.println(accountData);
        iv.setImageResource(accountData.getImageid());
        tv_type.setText(accountData.getName());
        String bbz = accountData.getBz();
        if (bbz == null) bbz = "添加备注";
        tv_bz.setText(bbz);
        tv_time.setText(accountData.getTime());
        String t = String.valueOf(accountData.getMoney());
        et.setText(t);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_record, container, false);
        initviews(view);
        loadGV();
        setGVlinster();
        if (model.equals("update")) {
            updateshow();
        } else {
            accountData.setName("其他");
            accountData.setImageid(R.mipmap.it_qita);
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowtime = simpleDateFormat.format(date);
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (model.equals("add")) {
            accountData.setTime(nowtime);
            tv_time.setText(nowtime);
            accountData.setYear(year);
            accountData.setMonth(month);
            accountData.setDay(day);
        }

        return view;
    }

    private void setGVlinster() {
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                adapter.selectPos = i;
                adapter.notifyDataSetInvalidated();
                TypeData ty = sin.get(i);
                tv_type.setText(ty.getName());
                iv.setImageResource(ty.getYi_id());
                accountData.setImageid(ty.getYi_id());
                accountData.setName(ty.getName());
            }
        });
    }

    private void loadGV() {
        sin = typeDataDao.findByKind(-1);
        adapter = new TypeDataAdapter(getContext(), sin);
        gv.setAdapter(adapter);
    }

private void initviews(View view) {
    my = view.findViewById(R.id.frag_record_jp);
    et = view.findViewById(R.id.frag_record_et);
    iv = view.findViewById(R.id.frag_record_iv);
    tv_type = view.findViewById(R.id.frag_record_type);
    tv_bz = view.findViewById(R.id.frag_record_bz);
    tv_time = view.findViewById(R.id.frag_record_time);
    gv = view.findViewById(R.id.frag_record_gv);
    tv_bz.setOnClickListener(this);
    tv_time.setOnClickListener(this);

    // 显示自定义软键盘
    Jianpan jp = new Jianpan(my, et);
    jp.show();
    jp.setOnEnsureListener(new Jianpan.OnEnsureListener() {
        @Override
        public void onEnsure() {
            String nowmoney = et.getText().toString();
            System.out.println(nowmoney + "***********");
            if (TextUtils.isEmpty(nowmoney) || nowmoney.equals("0")) {
                getActivity().finish();
                return;
            }
            accountData.setMoney(Float.parseFloat(nowmoney));
            System.out.println(accountData);
            AddData();
            getActivity().finish();
            return;
        }
    });

    // 为备注输入框设置 OnEditorActionListener
    EditText bzEditText = view.findViewById(R.id.frag_record_bz);
    bzEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                String bz = v.getText().toString();
                if (!TextUtils.isEmpty(bz)) {
                    accountData.setBz(bz);
                    tv_bz.setText(bz);
                    Toast.makeText(getContext(), "备注已添加: " + bz, Toast.LENGTH_SHORT).show();
                }
                // 隐藏键盘
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                // 隐藏光标
                v.clearFocus();
                return true;
            }
            return false;
        }
    });

    // 为备注输入框设置 OnFocusChangeListener
    bzEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                EditText editText = (EditText) v;
                String text = editText.getText().toString();
                if (!TextUtils.isEmpty(text)) {
                    editText.setSelection(text.length());
                }
            }
        }
    });
}


    private void AddData() {
        accountData.setType(1);
        if (model.equals("add"))
            accountDataDao.insertAccountData(accountData);
        else accountDataDao.Update(accountData);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.frag_record_bz:
                System.out.println("点击了备注");
                ShowBZ();
                break;
            case R.id.frag_record_time:
                System.out.println("点击了时间");
                showTime();
                break;
        }
    }

    String ttime;

    private void showTime() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = View.inflate(getContext(), R.layout.dialog_time, null);
        final DatePicker datePicker = view.findViewById(R.id.dialog_time_dp);
        final EditText hourEditText = view.findViewById(R.id.dialog_time_et_hour);
        final EditText minuteEditText = view.findViewById(R.id.dialog_time_et_minute);
        final Button cancelButton = view.findViewById(R.id.dialog_time_btn_cancel);
        final Button ensureButton = view.findViewById(R.id.dialog_time_btn_ensure);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        // 设置 EditText 内容为当前系统时间的小时和分钟
        hourEditText.setText(String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
        minuteEditText.setText(String.format("%02d", cal.get(Calendar.MINUTE)));

        builder.setView(view);

        final AlertDialog dialog = builder.create();
        dialog.show();

        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });

        ensureButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onClick(View v) {
                String hour = hourEditText.getText().toString();
                String minute = minuteEditText.getText().toString();

                if (TextUtils.isEmpty(hour) || TextUtils.isEmpty(minute)) {
                    Toast.makeText(getContext(), "请输入有效的时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                int hourInt = Integer.parseInt(hour);
                int minuteInt = Integer.parseInt(minute);

                if (hourInt < 0 || hourInt > 23 || minuteInt < 0 || minuteInt > 59) {
                    Toast.makeText(getContext(), "请输入有效的时间", Toast.LENGTH_SHORT).show();
                    return;
                }

                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d-%02d-%02d",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
                sb.append("  ");
                sb.append(String.format("%02d:%02d", hourInt, minuteInt));

                ttime = sb.toString();
                System.out.println(ttime);
                tv_time.setText(ttime);
                accountData.setYear(datePicker.getYear());
                accountData.setMonth(datePicker.getMonth() + 1);
                accountData.setDay(datePicker.getDayOfMonth());
                accountData.setTime(ttime);
                dialog.cancel(); // 取消dialog
            }
        });
    }

    private void ShowBZ() {
        // 获取EditText中的输入内容
        EditText edit_text = getView().findViewById(R.id.frag_record_bz);
        String bz = edit_text.getText().toString();

        // 设置备注到accountData
        accountData.setBz(bz);
        // 更新UI
        tv_bz.setText(bz);
//        Toast.makeText(getContext(), "备注已添加: " + bz, Toast.LENGTH_SHORT).show();
    }
}